package javaweb.web;

import javaweb.pojo.Book;
import javaweb.pojo.Cart;
import javaweb.pojo.CartItem;
import javaweb.servlet.impl.BaseServlet;
import javaweb.servlet.impl.BookServletImpl;
import javaweb.utility.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author shkstart
 * @creat -08-07 16:03
 */
public class CartServlet extends BaseServlet {
    private BookServletImpl bs = new BookServletImpl();
    protected void upDate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = WebUtils.parseInt(request.getParameter("id"), 0);
        int count = WebUtils.parseInt(request.getParameter("cont"), 0);
        Cart cart = (Cart)request.getSession().getAttribute("cart");
if (cart!=null){
    cart.upDateCount(id,count);
    String referer = request.getHeader("Referer");
    response.sendRedirect(referer);
}
    }
    protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       Cart cart = (Cart)request.getSession().getAttribute("cart");
       if (cart!=null){
           cart.clear();
       }
       // String referer = request.getHeader("Referer");
        response.sendRedirect(request.getContextPath()+"/pages/cart/cart.jsp");
    }
    protected void deleteItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = WebUtils.parseInt(request.getParameter("id"), 0);
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart != null) {
            bs.detleteBookId(id);
        }
        String referer = request.getHeader("Referer");
        response.sendRedirect(referer);
    }
    public void addItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = WebUtils.parseInt(request.getParameter("id"), 0);
        Book book = bs.queryBookId(id);
        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null) {
            Cart cart1 = new Cart();
            request.getSession().setAttribute("cart", cart1);
            cart1.addItem(cartItem);
        } else {
            cart.addItem(cartItem);
        }
        String referer = request.getHeader("Referer");
        request.getSession().setAttribute("last",cartItem.getName());
        response.sendRedirect(referer);



    }
}
